import { FileListener } from './fileListener';
import { UploadManager } from './uploadManager';

// 全局实例
let fileListenerWithUpload: FileListener | null = null;
let uploadManager: UploadManager | null = null;

export async function testFileListenerWithUpload(): Promise<void> {
  console.log('🧪 开始文件监听器 + 上传功能测试...');
  
  if (!window.electronAPI) {
    console.error('❌ electronAPI 不可用');
    return;
  }

  // 停止现有的监听器
  if (fileListenerWithUpload) {
    fileListenerWithUpload.stop();
    fileListenerWithUpload = null;
  }

  // 读取配置
  let config: any = {};
  try {
    config = await window.electronAPI.getConfig();
    console.log('📋 读取到配置:', config);
  } catch (error) {
    console.error('❌ 读取配置失败:', error);
    return;
  }

  // 验证配置
  if (!config.apiKey) {
    console.log('❌ 配置中未找到API密钥');
    console.log('💡 请先在应用中登录并保存配置');
    return;
  }

  if (!config.watchDirectory) {
    console.log('❌ 配置中未找到监听目录');
    console.log('💡 请先在应用中设置监听目录');
    return;
  }

  console.log(`🔑 使用API密钥: ${config.apiKey.substring(0, 10)}...`);
  console.log(`📁 使用监听目录: ${config.watchDirectory}`);

  // 创建上传管理器
  uploadManager = new UploadManager({
    apiKey: config.apiKey,
    maxConcurrentUploads: 2,
    onTaskStart: (task) => {
      console.log(`🚀 上传开始: ${task.fileInfo.name} (任务ID: ${task.id})`);
    },
    onTaskProgress: (task) => {
      console.log(`📊 上传进度: ${task.fileInfo.name} - ${task.progress}%`);
    },
    onTaskComplete: (task) => {
      console.log(`✅ 上传完成: ${task.fileInfo.name}`);
      console.log(`   响应:`, task.response);
    },
    onTaskError: (task) => {
      console.error(`❌ 上传失败: ${task.fileInfo.name} - ${task.error}`);
    }
  });

  console.log(`💡 提示：现在可以在监听目录中创建图片文件来测试自动上传功能`);

  // 创建文件监听器（启用自动上传）
  fileListenerWithUpload = new FileListener({
    directoryPath: config.watchDirectory,
    interval: 1000, // 1秒间隔用于测试
    autoUpload: true,
    uploadManager: uploadManager,
    onNewFile: (file) => {
      console.log(`📁 发现新文件，准备自动上传: ${file.name}`);
    },
    onError: (error) => {
      console.error('❌ 文件监听器错误:', error);
    }
  });

  // 启动监听器
  fileListenerWithUpload.start().then(() => {
    console.log('✅ 文件监听器 + 自动上传已启动');
    console.log('📝 现在可以在测试目录中创建图片文件来测试自动上传');
    console.log('💡 测试完成后，运行 stopFileListenerWithUpload() 停止监听器');
    console.log('💡 运行 getUploadStatus() 查看上传状态');
  }).catch((error) => {
    console.error('❌ 启动文件监听器失败:', error);
  });
}

export function stopFileListenerWithUpload(): void {
  if (fileListenerWithUpload) {
    fileListenerWithUpload.stop();
    fileListenerWithUpload = null;
    console.log('✅ 文件监听器已停止');
  } else {
    console.log('ℹ️ 没有正在运行的文件监听器');
  }
  
  uploadManager = null;
}

export function getUploadStatus(): void {
  if (!uploadManager) {
    console.log('ℹ️ 没有活动的上传管理器');
    return;
  }

  const stats = uploadManager.getStats();
  console.log('📊 上传状态统计:');
  console.log(`  总任务数: ${stats.total}`);
  console.log(`  待上传: ${stats.pending}`);
  console.log(`  上传中: ${stats.uploading}`);
  console.log(`  已完成: ${stats.completed}`);
  console.log(`  失败: ${stats.failed}`);

  const tasks = uploadManager.getAllTasks();
  if (tasks.length > 0) {
    console.log('\\n📋 任务详情:');
    tasks.forEach(task => {
      const statusIcon = {
        'pending': '⏳',
        'uploading': '🚀',
        'completed': '✅',
        'failed': '❌'
      }[task.status];
      
      console.log(`  ${statusIcon} ${task.fileInfo.name} (${task.status})`);
      if (task.error) {
        console.log(`     错误: ${task.error}`);
      }
    });
  }
}

export function cleanupCompletedUploads(): void {
  if (uploadManager) {
    uploadManager.cleanupCompletedTasks();
    console.log('✅ 已清理完成的上传任务');
  } else {
    console.log('ℹ️ 没有活动的上传管理器');
  }
}

// 开发环境：自动注册全局函数
if (typeof window !== 'undefined' && process.env.NODE_ENV === 'development') {
  (window as any).testFileListenerWithUpload = testFileListenerWithUpload;
  (window as any).stopFileListenerWithUpload = stopFileListenerWithUpload;
  (window as any).getUploadStatus = getUploadStatus;
  (window as any).cleanupCompletedUploads = cleanupCompletedUploads;
  
  console.log('💡 文件监听器 + 上传功能测试工具已加载');
  console.log('可用函数:');
  console.log('  testFileListenerWithUpload() - 启动文件监听器+自动上传测试');
  console.log('  stopFileListenerWithUpload() - 停止监听器');
  console.log('  getUploadStatus() - 查看上传状态');
  console.log('  cleanupCompletedUploads() - 清理已完成的任务');
}